//
// Created by NilYang<nil.yang@qq.com> on 2022/8/4.
//
#include <fstream>
#include <iostream>
#include <string>
#include <random>
#include "unix2dos.h"

namespace convert {
    using namespace std;
    constexpr int MY_MIN = 10000;
    constexpr int MY_MAX = 100000000;
    //constexpr int RAND_NUMS_TO_GENERATE = 10;
    // NOLINT
    const string MY_FLAG_DOS2UNIX = "d2u";
    // NOLINT
    const string MY_FLAG_UNIX2DOS = "u2d";

    int unix2dos(int argc, char **argv) {
        string filename;
        string flag;
        char c;
        if (argc == 3) {
            flag = argv[1];
            filename = argv[2];
        } else {
            string echo = "echo \"\n参数错误，请检查\"\necho\n"
                          "echo \"用法: crlf-tool [转换类型] [文件路径]\"\necho\n"
                          "echo \"                 转换类型 可选值：u2d [unix to dos] 或 d2u [dos to unix]\"\n"
                          "echo \"                 文件路径 待转换路径\n\"\n"
                          "echo \"例子1： crlf-tool u2d  foo.bat 将foo.bat转为dos格式\"\n"
                          "echo \"例子2： crlf-tool d2u  foo.sh 将foo.sh转为unix格式\n\n\"";

            system(echo.c_str());
            return EXIT_FAILURE;
        }
        string tmpFile;
        tmpFile = "/tmp/temp-" + to_string(makeRandomNumber()) + ".txt";
        ifstream is(filename.c_str(), ios::binary);
        ofstream os(tmpFile, ios::binary);
        while (is.get(c)) {
            switch (c) {
                case 0x0d:
                    break;
                case 0x0a:
                    if (MY_FLAG_DOS2UNIX == flag) {
                        os.put((char) 0x0a);
                    } else if (MY_FLAG_UNIX2DOS == flag) {
                        os.put((char) 0x0d);
                        os.put((char) 0x0a);
                    }
                    break;
                default:
                    os.put(c);
                    break;
            }
        }
        is.close();
        os.close();
        string command = "mv " + tmpFile + " " + filename;
        string echo = "echo " + command + "\necho\n";
        system(echo.c_str());

        return system(command.c_str());
    }

    int makeRandomNumber() {
        // 生成随机临时文件名
        random_device rd;
        default_random_engine eng(rd());
        uniform_int_distribution<int> distr(MY_MIN, MY_MAX);
        return distr(eng);
    }
}